const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const Cr = Components.results;

Cu.import("resource://gre/modules/Services.jsm");

function openidLogStringMessage(msg) {
//  Services.console.logStringMessage(msg);
}

// Called once when the dialog displays
function onLoad() {
//	openidLogStringMessage("chooseImage onLoad start");
	try {
	  var nameTextbox = document.getElementById("openid-name");
    nameTextbox.addEventListener("change", onchange, false);
    nameTextbox.addEventListener("input", oninput, false);
	} catch (e) {
	  Components.utils.reportError(e);
	}
	try {
		var image = document.getElementById("image");
//		image.setAttribute("width", 16);
//		image.setAttribute("height", 16);
		var OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1']
			.getService().wrappedJSObject;
		var realm = window.arguments[0].host;
		var claimed_id = window.arguments[0].claimedid;
		var dataUrl = OpenIdStorage.getImage(claimed_id, null);
		if (dataUrl) {
//			openidLogStringMessage("onLoad dataUrl=" + dataUrl);
//			image.setAttribute("src", "chrome://openidnascar/content/openid-16x16.gif");
			image.setAttribute("src", dataUrl);
		} else {
//			openidLogStringMessage("onLoad !dataUrl");
		}
		var openidname = OpenIdStorage.getOpenIDName(claimed_id, null);
//		openidLogStringMessage("onLoad openidname="+openidname);
		if (openidname) {
			var openidnameElt = document.getElementById("openid-name");
			openidnameElt.setAttribute("value", openidname);
		}
		openidLoadFavicon(claimed_id);
	} catch(e) {
	  Components.utils.reportError(e);
	}	
}

// Called once if and only if the user clicks OK
function onOK() {
   return true;
}

function imageOnError() {
	var image = document.getElementById("image");
	openidLogStringMessage("ERROR image.src = " + image.getAttribute("src"));
}

function oninput(event) {
  try {
//    openidLogStringMessage("chooseimage ininput value=");
    var elt = document.getElementById("openid-name");
    var value = elt.value;
//    openidLogStringMessage("chooseimage ininput value=" + value);
  } catch(e) {
    Components.utils.reportError(e);
  }
}

function onchange(event) {
    try {
    var elt = document.getElementById("openid-name");
    var value = elt.value;
//    openidLogStringMessage("chooseimage onchange value=" + value);
    if (value && (value.trim() != "")) {
      try {
        var OpenIdStorage = Components.classes['@openinfocard.com/openidstorage;1']
            .getService().wrappedJSObject;
        var claimed_id = window.arguments[0].claimedid;
        var realm = window.arguments[0].host;
//        openidLogStringMessage("chooseimage onchange claimed_id="
//            + claimed_id + " realm=" + realm + " name=" + value);
        OpenIdStorage.setOpenIDName(claimed_id, realm, value);
      } catch (ex) {
        Components.utils.reportError(e);
      }
    }
  } catch (e) {
    Components.utils.reportError(e);
  }
}

function openidfaviconOnclick(event) {
//  openidLogStringMessage("openidfaviconOnclick");
  try {
    var image = document.getElementById("openidfavicon");
    if (!image) {
//      openidLogStringMessage("openidfaviconOnclick !image");
      return;
    }
    image.addEventListener("click", openidfaviconOnclick, true);
    var value = image.src;
    image = document.getElementById("image");
    image.setAttribute("src", value);
  } catch (e) {
    Components.utils.reportError(e);
  }
}

function openidfaviconOnError() {
  openidLogStringMessage("openidfaviconOnError");
}

function openidfaviconOnLoad() {
  openidLogStringMessage("openidfaviconOnLoad");
  try {
    var image = document.getElementById("openidfavicon");
    if (!image) {
      openidLogStringMessage("openidfaviconOnLoad !image");
      return;
    }
    image.addEventListener("click", openidfaviconOnclick, true);
  } catch (e) {
    Components.utils.reportError(e);
  }
}

function openidLoadFavicon(claimed_id) {
  try {
    openidLogStringMessage("openidLoadFavicon claimed_id=" + claimed_id);
    var image = document.getElementById("openidfavicon");
    if (!image) {
      openidLogStringMessage("openidLoadFavicon !image");
      return;
    }
    image.addEventListener("load", openidfaviconOnLoad, true);
    image.addEventListener("error", openidfaviconOnError, true);
    var faviconService = Components.classes["@mozilla.org/browser/favicon-service;1"]
        .getService(Components.interfaces.nsIFaviconService);
    var pageSpec = unescape(claimed_id);
    openidLogStringMessage("openidLoadFavicon pageSpec=" + pageSpec);
    var pageUri = Services.io.newURI(pageSpec, null, null);
    var faviconUri = faviconService.getFaviconImageForPage(pageUri);
    if (faviconUri && (faviconUri.spec != "chrome://mozapps/skin/places/defaultFavicon.png")) {
      openidLogStringMessage("openidLoadFavicon faviconUri.spec=" + faviconUri.spec);
      image.setAttribute("src", faviconUri.spec);
    } else {
      openidLogStringMessage("openidLoadFavicon NO faviconUri! for " + pageUri.spec);
      pageSpec = pageUri.prePath;
      openidLogStringMessage("openidLoadFavicon pageSpec=" + pageSpec);
      pageUri = Services.io.newURI(pageSpec, null, null);
      faviconUri = faviconService.getFaviconImageForPage(pageUri);
      if (faviconUri && (faviconUri.spec != "chrome://mozapps/skin/places/defaultFavicon.png")) {
        openidLogStringMessage("openidLoadFavicon faviconUri.spec=" + faviconUri.spec);
        image.setAttribute("src", faviconUri.spec);
      } else {
        openidLogStringMessage("openidLoadFavicon NO faviconUri! for " + pageUri.spec);
        pageSpec = pageSpec + "/favicon.ico";
        openidLogStringMessage("openidLoadFavicon setting icon to " + pageSpec);
        image.setAttribute("src", pageSpec);
      }
    }
  } catch (e) {
    Components.utils.reportError(e);
  }
}

function imageOnLoad() {
  try {
    var callback = window.arguments[1];
    var realm = window.arguments[0].host;
    var claimed_id = window.arguments[0].claimedid;
    var image = document.getElementById("image");
    Components.utils.import("resource://openidnascar/image.jsm");
    storeOpenIdImage(null, realm, claimed_id, image, callback);
	} catch(e) {
	  Components.utils.reportError(e);
	}
}

function getFile() {
	const nsIFilePicker = Components.interfaces.nsIFilePicker;
	
	var fp = Components.classes["@mozilla.org/filepicker;1"]
		           .createInstance(nsIFilePicker);
	fp.init(window, "Dialog Title", nsIFilePicker.modeOpen);
	fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
	
	var rv = fp.show();
	if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
	  var file = fp.file;
	  // Get the path as string. Note that you usually won't
	  // need to work with the string paths.
	  var path = fp.file.path;
	  var ios = Components.classes["@mozilla.org/network/io-service;1"].
	            getService(Components.interfaces.nsIIOService);
	  var URL = ios.newFileURI(file);
	  document.getElementById("image").setAttribute("src", URL.spec);
//    openidLogStringMessage("path = " + path + " url = " + URL.spec);

	  document.getElementById("image").setAttribute("src", URL.spec);

	} else {
	  document.getElementById("image").setAttribute("src", "");
	}
}